package com.example.common.tools

import android.app.Activity
import android.app.Application
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.ContextWrapper
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import android.os.Build
import android.os.Environment
import android.provider.Settings
import android.text.Spannable
import android.text.SpannableString
import android.text.style.ForegroundColorSpan
import android.util.Base64
import android.util.DisplayMetrics
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.Button
import android.widget.TextView
import com.example.common.widget.LoadingDialog
import java.io.ByteArrayInputStream
import java.security.MessageDigest
import java.security.NoSuchAlgorithmException
import java.security.cert.CertificateFactory
import java.security.cert.X509Certificate
import java.util.regex.Matcher
import java.util.regex.Pattern

/**
 * Describe : 快速开发工具集合
 */
object TooldUtils {

    private var mApplicationContext: Application? = null
    private var yLoadingDialog: LoadingDialog? = null
    private var mAppExecutors: AppExecutors? = null

    fun initialize(app: Application?) {
        mApplicationContext = app
        mAppExecutors = AppExecutors()
    }

    fun getAppExecutors(): AppExecutors? {
        return mAppExecutors
    }

    fun getApplication(): Application? {
        return mApplicationContext
    }

    /**
     * 获取屏幕宽度
     */
    fun getScreenWidth(): Int {
        val dm = DisplayMetrics()
        ActivityUtil.currentActivity!!.windowManager.defaultDisplay.getMetrics(dm)
        return dm.widthPixels
    }

    /**
     * 获取屏幕高度
     */
    fun getScreenHeight(): Int {
        val dm = DisplayMetrics()
        ActivityUtil.currentActivity!!.windowManager.defaultDisplay.getMetrics(dm)
        return dm.heightPixels
    }

    /**
     * Loading加载框
     */
    fun showLoading(activity: Activity?, msg: String) {
        if (activity != null && !activity!!.isFinishing) {
            yLoadingDialog = LoadingDialog.buildDialog(activity, msg)
            yLoadingDialog!!.showLoading()
        }
    }

    /**
     * dismissLoading
     */
    fun dismissLoading() {
        yLoadingDialog?.hideLoading()
        yLoadingDialog = null
    }

    /**
     * 根据时间休眠然后关闭当前页面
     * 比如：5秒自动返回
     * 或者只需要后台给一个结果而已
     */
    fun finishBySleep(millis: Long) {
        object : Thread() {
            override fun run() {
                try {
                    sleep(millis)
                    ActivityUtil.currentActivity?.finish()
                } catch (e: InterruptedException) {
                    e.printStackTrace()
                }
            }
        }.start()
    }

    /**
     * 获取版本名
     */
    fun getVersionName(): String? {
        return try {
            val packageManager = getApplication()!!.packageManager
            val packageInfo = packageManager.getPackageInfo(getApplication()!!.packageName, 0)
            packageInfo.versionName
        } catch (e: PackageManager.NameNotFoundException) {
            e.printStackTrace()
            null
        }
    }

    /**
     * 获取版本号
     */
    fun getVersionCode(): Int {
        return try {
            val packageManager = getApplication()!!.packageManager
            val packageInfo = packageManager.getPackageInfo(getApplication()!!.packageName, 0)
            packageInfo.versionCode
        } catch (e: PackageManager.NameNotFoundException) {
            e.printStackTrace()
            0
        }
    }

    /**
     * 检验手机号
     */
    fun checkPhoneNumber(mobiles: String?): Boolean {
        var p: Pattern? = null
        var m: Matcher? = null
        var b = false
        p = Pattern.compile("^[1][3,4,5,6,7,8,9][0-9]{9}$")
        m = p.matcher(mobiles)
        b = m.matches()
        return b
    }

    /**
     * MD5加密
     */
    fun MD5(data: String): String {
        var md5: MessageDigest? = null
        try {
            md5 = MessageDigest.getInstance("MD5")
        } catch (e: NoSuchAlgorithmException) {
            e.printStackTrace()
        }
        md5!!.update(data.toByteArray())
        val m = md5.digest()
        return Base64.encodeToString(m, Base64.DEFAULT)
    }

    /**
     * dp2px
     */
    fun dp2px(dp: Float): Int {
        val density = getApplication()!!.resources.displayMetrics.density
        return (dp * density + 0.5f).toInt()
    }

    /**
     * px2dp
     */
    fun px2dp(px: Int): Float {
        val density = getApplication()!!.resources.displayMetrics.density
        return px / density
    }

    /**
     * 复制文本到粘贴板
     */
    fun copyToClipboard(text: String?) {
        if (Build.VERSION.SDK_INT >= 11) {
            val cbm = getApplication()!!.getSystemService(Activity.CLIPBOARD_SERVICE) as ClipboardManager
            cbm.setPrimaryClip(ClipData.newPlainText(getApplication()!!.packageName, text))
        } else {
            val cbm = getApplication()!!.getSystemService(Activity.CLIPBOARD_SERVICE) as android.text.ClipboardManager
            cbm.text = text
        }
    }

    /**
     * 字体高亮
     */
    fun Foreground(view: View?, color: Int, start: Int, end: Int): View? {
        if (view is Button) {
            val btn = view
            // 获取文字
            val span: Spannable = SpannableString(btn.text.toString())
            //设置颜色和起始位置
            span.setSpan(ForegroundColorSpan(color), start, end, Spannable.SPAN_INCLUSIVE_EXCLUSIVE)
            btn.text = span
            return btn
        } else if (view is TextView) { //EditText extends TextView
            val text = view
            val span: Spannable = SpannableString(text.text.toString())
            span.setSpan(ForegroundColorSpan(color), start, end, Spannable.SPAN_INCLUSIVE_EXCLUSIVE)
            text.text = span
            return text
        }
        return null
    }

    /**
     * 关闭软键盘
     */
    fun closeSoftKeyboard() {
        val inputManger = ActivityUtil.currentActivity?.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        inputManger.hideSoftInputFromWindow(
            ActivityUtil.currentActivity!!.window.decorView.windowToken,
            0
        )
    }

    /**
     * 获取android ID
     */
    fun getAndroidID(): String {
        val id = Settings.Secure.getString(
            mApplicationContext!!.contentResolver,
            Settings.Secure.ANDROID_ID
        )
        return id ?: ""
    }

    /**
     * 获取app签名秘钥
     */
    fun getAppSignSha1():String{
        try {
            val packageManager: PackageManager = mApplicationContext!!.packageManager
            val packageInfo: PackageInfo = packageManager.getPackageInfo(mApplicationContext!!.packageName, PackageManager.GET_SIGNATURES)
            // X509证书，X.509是一种非常通用的证书格式
            val signs = packageInfo.signatures
            val sign = signs[0]
            val certFactory = CertificateFactory.getInstance("X.509")
            val cert = certFactory.generateCertificate(ByteArrayInputStream(sign.toByteArray())) as X509Certificate // md5
            val md = MessageDigest.getInstance("SHA1")
            //获得公钥
            val b = md.digest(cert.encoded)
            return byte2HexFormatted(b)
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return ""

    }

    //转换成字符
    private fun byte2HexFormatted( arr: ByteArray): String {
        val str = StringBuilder(arr.size * 2)
        for (i in arr.indices) {
            var h = Integer.toHexString(arr[i].toInt())
            val l = h.length
            if (l == 1) h = "0$h"
            if (l > 2) h = h.substring(l - 2, l)
            str.append(h.toUpperCase())
            if (i < arr.size - 1) str.append(':')
        }
        return str.toString()
    }

    /**
     * 获取声音目录
     */
    fun getRingtonesPath():String{
        var cw =  ContextWrapper(mApplicationContext)
        var directory = cw.getExternalFilesDir(Environment.DIRECTORY_RINGTONES)
        return directory!!.absolutePath
    }

    /**
     * 获取下载目录
     */
    fun getDownPath():String{
        var cw =  ContextWrapper(mApplicationContext)
        var directory = cw.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)
        return directory!!.absolutePath
    }

    /**
     * 获取图片目录
     */
    fun getPicPath():String{
        var cw =  ContextWrapper(mApplicationContext)
        var directory = cw.getExternalFilesDir(Environment.DIRECTORY_PICTURES)
        return directory!!.absolutePath
    }


}

